<template>
  <div class="rzgl-main">
    <ComTable :tableimg="tableimg" :tabletext="tabletext" :isleft="isleft" :istree="istree" :activedata='leftdata'
      :leftActiveLogIndex="activeLogIndex" :issearchbtn="issearchbtn" :searchbtn="searchbtn"
      :istablerightbtn="istablerightbtn" :tablerightbtn="tablerightbtn" :istablecolbtn="istablecolbtn"
      :tablecolbtn="tablecolbtn" :tablerightfrom="tablerightfrom" :tablerightfromvalue="currentFormConfig"
      :tableData="tableData" />
  </div>

  <Eldioa :headtext="Eldioaform.headtext" :dialogVisible="editdialogVisible" @eddialogVisible="updateDialogVisible"
    :elwidth="Eldioaform.elwidth" :elheight="Eldioaform.elheight">
    <template #dialogbody>
      <Elfrom :form-config="editformdataconfig" v-model="editform" :show-actions="false" @elsubmit="editsub"
        ref="editformRef" />

      <div class="dialog-footer" style="text-align: right;">
        <el-button type="primary" style="background: rgba(4, 134, 254, 1);" @click="handleSubmit">
          确认
        </el-button>
        <el-button style="background: transparent;border:1px solid rgba(89, 175, 249, 0.70);color:rgba(1, 194, 255, 1)"
          @click="handleCancel">
          取消
        </el-button>
      </div>

    </template>
  </Eldioa>
</template>

<script setup>
import { ref, provide, onMounted, computed } from 'vue'
import {
  getpersonlist, postpersonadd, putpersonupdate, delpersonid, getpersonType,
  getteamlist, postteamadd, putteamupdate, delteamid,
  getteamType,
  getteamGroup,
  getmaterialist, postmaterialadd, putmaterialupdate, delmaterialid,
  getteamName,
  getinstitutionlist, postinstitutionadd, putinstitutionupdate, delinstitutionid, getmaterialType,
  getinstitutionName,
  getdevicelist, postdeviceadd, putdeviceupdate, deldeviceid,
  gettraininglist, posttrainingadd, puttrainingupdate, deltrainingid
} from '@/api'
import ComTable from '@/components/table/index.vue'
import tableImgSrc from '@/assets/img/components/headicon.png'
import Eldioa from '@/components/eldioa/index.vue'
import Elfrom from '@/components/elfrom/index.vue'
import formConfig from './shformconfig'
// 弹窗名称和icon
const tableimg = ref(tableImgSrc)
const tabletext = ref('数据管理')


const Eldioaform = ref({
  headtext: '新增用户',
  elwidth: 746,
  elheight: 500,
  formtype: '新增'
})

const editdialogVisible = ref(false)

const updateDialogVisible = (newValue) => {
  editdialogVisible.value = newValue
  resetFieldsform(editform.value, editformdata.value)
}

const editformRef = ref()

/* 
左侧
isleft 是否显示 左侧数据
istree  是否显示 树形结构
leftdata  左侧数据
btnactivindex  点击之后的数据
*/
const istree = ref(false)
const isleft = ref(true)

const leftdata = ref([
  { label: '训练管理' },
  { label: '模拟训练数据管理' },
  { label: '救援决策数据管理' },
  { label: '设备管理' },
  { label: '人员管理' },
  { label: '队伍管理' },
  { label: '物资管理' },
  { label: '机构管理' },
])

// 当前选中的日志类型索引
const activeLogIndex = ref('训练管理')

// 根据当前选中的日志类型动态返回表单配置
const currentFormConfig = computed(() => {
  let formConfigdata = null
  switch (activeLogIndex.value) {
    case '人员管理':
      formConfigdata = formConfig.searchPersonManagement
      break;
    case '队伍管理':
      formConfigdata = formConfig.searchTeamManagement
      break;
    case '物资管理':
      formConfigdata = formConfig.searchMaterialManagement
      break;
    case '机构管理':
      formConfigdata = formConfig.searchInstitutionManagement
      break;
    case '设备管理':
      formConfigdata = formConfig.searchEquipmentManagement
      break;
    case '训练管理':
      formConfigdata = formConfig.searchTrainManagement
      break;
  }

  return formConfigdata
})

// 根据当前选中的日志类型动态返回表单数据模型
const currentFormData = computed(() => {
  let formconfigdata = null
  switch (activeLogIndex.value) {
    case '人员管理':
      formconfigdata = formConfig.searchPersonManagementform
      break;
    case '队伍管理':
      formconfigdata = formConfig.searchTeamManagementform
      break;
    case '物资管理':
      formconfigdata = formConfig.searchMaterialManagementform
      break;
    case '机构管理':
      formconfigdata = formConfig.searchInstitutionManagementform
      break;
    case '设备管理':
      formconfigdata = formConfig.searchEquipmentManagementform
      break;
    case '训练管理':
      formconfigdata = formConfig.searchTrainManagementform
      break;
  }
  return formconfigdata
})

const btnactivindex = async (data) => {
  console.log(data)
  tablerightfrom.value = {}
  // 更新当前选中的日志类型索引
  activeLogIndex.value = data.label
  Eldioaform.value.headtext = ''
  Eldioaform.value.formtype = ''
  switch (activeLogIndex.value) {
    case '人员管理':
      Eldioaform.value.elheight = 400
      const temname = await getteamName()
      const personType = await getpersonType()
      formConfig.PersonManagement[3].columns[1].options = temname.data
      formConfig.PersonManagement[2].columns[1].options = personType.data
      formConfig.searchPersonManagement[2].options = personType.data
      break;
    case '队伍管理':
      Eldioaform.value.elheight = 300
      const teamType = await getteamType()
      const teamGroup = await getteamGroup()
      formConfig.TeamManagement[0].columns[1].options = teamType.data
      formConfig.TeamManagement[2].columns[1].options = teamGroup.data
      formConfig.searchTeamManagement[1].options = teamType.data
      formConfig.searchTeamManagement[2].options = teamGroup.data
      break;
    case '物资管理':
      Eldioaform.value.elheight = 200
      const institutionName = await getinstitutionName()
      const materialType = await getmaterialType()
      formConfig.MaterialManagement[1].columns[0].options = institutionName.data
      formConfig.searchMaterialManagement[2].options = institutionName.data
      formConfig.MaterialManagement[0].columns[1].options = materialType.data
      formConfig.searchMaterialManagement[1].options = materialType.data
      break;
    case '机构管理':
      Eldioaform.value.elheight = 300
      break;
    case '设备管理':
      Eldioaform.value.elheight = 400
      break;
    case '训练管理':
      Eldioaform.value.elheight = 500
      break;
  }

  // 重置表单数据
  resetFieldsform(tablerightfrom.value, currentFormData.value)


  // 重新获取数据
  getuserlistapi()
}
provide('btnactivindex', btnactivindex)

/* 
右侧
tablerightfrom 表单数据
tablerightfromvalue 动态表单属性(查询表单)

searchbtnfun  右侧头部查询按钮点击事件回调
issearchbtn  是否显示右侧头部查询按钮
searchbtn  右侧头部按钮数据

istablerightbtn  是否显示最右侧头部按钮
tablerightbtn  最右侧头部按钮数据

istablecolbtn  是否显示表格列按钮
tablecolbtn  表格列按钮数据
untablecolbtn 表格列按钮数据回调

tableData 表格数据
pageChange 分页改变
pageSizeChange 每页条数改变
*/



const searchbtnfun = (data) => {
  console.log('searchbtnfun', data)
  switch (data.name) {
    case '检索':
      tablerightfrom.value.page = 1
      tablerightfrom.value.pageSize = 15
      getuserlistapi(tablerightfrom.value)
      break;
    case '重置':
      // 根据当前日志类型重置表单
      resetFieldsform(tablerightfrom.value, currentFormData.value)
      getuserlistapi()
      break;
    case '新增':
      resetFieldsform(editform.value, editformdata.value)
      editdialogVisible.value = true
      Eldioaform.value.headtext = '新增用户'
      Eldioaform.value.formtype = '新增'
      if (editformRef.value) {

        setTimeout(() => {
          editformRef.value?.clearValidate()
        }, 100)
      }

      break;
  }
}

provide('searchbtnfun', searchbtnfun)

// 右侧头部表单，动态按钮
const issearchbtn = ref(true)

const searchbtn = ref([
  {
    name: '检索',
    type: 'primary'
  },
  {
    name: '重置',
    type: ''
  }
])

const tablerightbtn = ref([
  {
    name: '新增',
    type: 'primary'
  },
  // {
  //   name: '删除',
  //   type: 'danger'
  // },
])


const istablerightbtn = ref(true)

const istablecolbtn = ref(true)

const tablecolbtn = ref([
  {
    name: '编辑',
    type: 'primary',
    islink: true
  },
  {
    name: '删除',
    type: 'danger',
    islink: true
  },

])

const untablecolbtn = async (data, row) => {
  console.log('单行表格数据', data, row)
  switch (data.name) {
    case '编辑':
      editdialogVisible.value = true
      Eldioaform.value.headtext = '编辑用户'
      Eldioaform.value.formtype = '编辑'
      resetFieldsform(editform.value, editformdata.value)
      // switch (activeLogIndex.value) {
      //   case '人员管理':
      //     Eldioaform.value.elheight = 400
      //     break;
      //   case '队伍管理':
      //     Eldioaform.value.elheight = 300
      //     break;
      //   case '物资管理':
      //     Eldioaform.value.elheight = 200
      //     break;
      //   case '机构管理':
      //     Eldioaform.value.elheight = 300
      //     break;
      //   case '设备管理':
      //     Eldioaform.value.elheight = 400

      //     break;
      //   case '训练管理':
      //     Eldioaform.value.elheight = 500
      //     break;

      // }
      formeditchange(editform.value, row, activeLogIndex.value)
      setTimeout(() => {
        editformRef.value?.clearValidate()
      }, 100)
      break;

    case '删除':
      switch (activeLogIndex.value) {
        case '人员管理':
          await delpersonid(row.id)
          break;
        case '队伍管理':
          await delteamid(row.id)
          break;
        case '物资管理':
          await delmaterialid(row.id)
          break;
        case '机构管理':
          await delinstitutionid(row.id)
          break;
        case '设备管理':

          await deldeviceid(row.id)
          break;
        case '训练管理':
          await deltrainingid(row.id)
          break;

      }
      getuserlistapi()
      break;


  }
}
provide('untablecolbtn', untablecolbtn)

const formeditchange = (form, row, type) => {
  // switch (type) {
  // case '人员管理':
  // 将 row 的所有属性值赋值给 form
  Object.assign(form, row);
  // break;
  // }
}




const tablerightfrom = ref({
  ...currentFormData.value
})

// 表格
const tableData = ref(null)

const SelectionChange = (data) => {
  console.log('change多选', data)
}
provide('SelectionChange', SelectionChange)

// 分页
const pageChange = async (page) => {
  await getuserlistapi({ page, pageSize: tableData.value.pageSize });
}
const pageSizeChange = async (pageSize) => {
  await getuserlistapi({ page: 1, pageSize });
}

provide('handlePageChange', pageChange)
provide('handlePageSizeChange', pageSizeChange)

const getuserlistapi = async (asdaa) => {
  let listdata = null
  switch (activeLogIndex.value) {
    case '人员管理':
      listdata = await getpersonlist({ ...tablerightfrom.value, page: asdaa?.page || 1, pageSize: asdaa?.pageSize || 15 })
      tableData.value = {
        tablename: tabletext.value,
        ...listdata.data
      }
      break;
    case '队伍管理':
      listdata = await getteamlist({ ...tablerightfrom.value, page: asdaa?.page || 1, pageSize: asdaa?.pageSize || 15 })
      tableData.value = {
        tablename: tabletext.value,
        ...listdata.data
      }
      break;
    case '物资管理':
      listdata = await getmaterialist({ ...tablerightfrom.value, page: asdaa?.page || 1, pageSize: asdaa?.pageSize || 15 })
      tableData.value = {
        tablename: tabletext.value,
        ...listdata.data
      }
      break;
    case '机构管理':
      listdata = await getinstitutionlist({ ...tablerightfrom.value, page: asdaa?.page || 1, pageSize: asdaa?.pageSize || 15 })
      tableData.value = {
        tablename: tabletext.value,
        ...listdata.data
      }
      break;
    case '设备管理':
      listdata = await getdevicelist({ ...tablerightfrom.value, page: asdaa?.page || 1, pageSize: asdaa?.pageSize || 15 })
      tableData.value = {
        tablename: tabletext.value,
        ...listdata.data
      }
      break;

    case '训练管理':
      listdata = await gettraininglist({ ...tablerightfrom.value, page: asdaa?.page || 1, pageSize: asdaa?.pageSize || 15 })
      tableData.value = {
        tablename: tabletext.value,
        ...listdata.data
      }
      break;



  }





}



//--------------
// 动态表单

const editformdataconfig = computed(() => {
  let formconfig = null
  switch (activeLogIndex.value) {
    case '人员管理':
      formconfig = formConfig.PersonManagement
      break;
    case '队伍管理':
      formconfig = formConfig.TeamManagement
      break;
    case '物资管理':
      formconfig = formConfig.MaterialManagement
      break;
    case '机构管理':
      formconfig = formConfig.InstitutionManagement
      break;
    case '设备管理':
      formconfig = formConfig.EquipmentManagement
      break;
    case '训练管理':
      formconfig = formConfig.TrainManagement
      break;

  }
  return formconfig

})

// 表单数据
const editformdata = computed(() => {
  let formdata = null
  switch (activeLogIndex.value) {
    case '人员管理':
      formdata = formConfig.PersonManagementdata
      break;
    case '队伍管理':
      formdata = formConfig.TeamManagementdata
      break;
    case '物资管理':
      formdata = formConfig.MaterialManagementdata
      break;
    case '机构管理':
      formdata = formConfig.InstitutionManagementdata
      break;
    case '设备管理':
      formdata = formConfig.EquipmentManagementdata
      break;
    case '训练管理':
      formdata = formConfig.TrainManagementdata
      break;
  }
  return formdata
})


// 表单数据
const editform = ref(
  { ...editformdata.value }
)



// 根据按钮属性提交表单
const editsub = async (editsubdata) => {
  console.log('editsubdata', editsubdata)
  switch (activeLogIndex.value) {
    case '人员管理':
      switch (Eldioaform.value.formtype) {
        case '新增':
          await postpersonadd(editsubdata)
          break;
        case '编辑':
          await putpersonupdate(editsubdata)
          break;
      }
      break;
    case '队伍管理':
      switch (Eldioaform.value.formtype) {
        case '新增':
          await postteamadd(editsubdata)
          break;
        case '编辑':
          await putteamupdate(editsubdata)
          break;
      }
      break;
    case '物资管理':
      switch (Eldioaform.value.formtype) {
        case '新增':
          await postmaterialadd(editsubdata)
          break;
        case '编辑':
          await putmaterialupdate(editsubdata)
          break;
      }
      break;
    case '机构管理':
      switch (Eldioaform.value.formtype) {
        case '新增':
          await postinstitutionadd(editsubdata)
          break;
        case '编辑':
          await putinstitutionupdate(editsubdata)
          break;
      }
      break;
    case '设备管理':
      switch (Eldioaform.value.formtype) {
        case '新增':
          await postdeviceadd(editsubdata)
          break;
        case '编辑':
          await putdeviceupdate(editsubdata)
          break;
      }
      break;
    case '训练管理':

      switch (Eldioaform.value.formtype) {

        case '新增':
          if (editsubdata.rollfile) {
            editsubdata.fileUrl = editsubdata.rollfile.raw
          }
          await posttrainingadd(editsubdata)
          break;
        case '编辑':
          if (editsubdata.rollfile) {
            if (Object.keys(editsubdata.rollfile).length != 0) {
              editsubdata.fileUrl = editsubdata.rollfile.raw
            }
          }
          await puttrainingupdate(editsubdata)
          break;
      }
      break;
  }

  editdialogVisible.value = false
  editformRef.value.resetFields()
  await getuserlistapi()
}


// 确认表单
const handleSubmit = async () => {
  if (!editformRef.value) return
  try {
    await editformRef.value.handleSubmit()
  } catch (error) {
    console.error('表单提交失败:', error)
  }
}
// 关闭
const handleCancel = () => {
  if (!editformRef.value) return
  editformRef.value.handleReset()
  resetFieldsform(editform.value, editformdata.value)
  editdialogVisible.value = false
}

// 重置表单
const resetFieldsform = (form, comform) => {
  Object.keys(form).forEach(key => {
    if (key in comform) {
      form[key] = comform[key]
    } else {
      form[key] = ''
    }
  })
}

onMounted(() => {
  getuserlistapi()
})

const tableformbtndata = (item) => {
  console.log('tableformbtndata', item)
  isJyjctable.value = false
}

provide('tablebtnfun', tableformbtndata)
</script>

<style lang="less" scoped>
:deep(.el-form-item__label) {
  color: #fff;
}
</style>